﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Linq;
using System.Text.RegularExpressions;
using MediaPortal.GUI.Library;
using MediaPortal.Dialogs;
using NLog;
using dlCentral.GUI.Items;
using dlCentral.Localizations;
using dlCentral.PluginHandlers;
using dlCentral.Settings;
using dlCentral.Settings.Data;
using dlCentral.Utils;
using dlCentral.Scrapper;

namespace dlCentral.GUI {
    public class dlCentralGUI : GUIWindow {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        private dlCentralCore core = dlCentralCore.Instance;
        private Retriever retriever = Retriever.Instance;

        public const int dlCentralGUIID = 181966;
        public readonly List<int> MainWindowIDs = new List<int> { 0, 34, 35, dlCentralGUIID };

        #region Private Variables
        private WaitCursor waitCursor;
        private int _lastSelectedSitesItemIndex = 0;
        private int _lastSelectedListItemIndex = 1;
        private bool _GUIInitialized = false;
        private bool _backupHandlerSet = false;
        private bool _notificationDone = false;
        private ItemSortMethod _listSortMethod = ItemSortMethod.ItemName;
        private bool _listSortAsc = true;
        private List<FileInfo> _subtitleFilesForCurrentMedia = new List<FileInfo>();
        #endregion

        #region GUI Controls
        [SkinControl((int)GUIControls.CANCELBUTTON)]
        protected GUIButtonControl cancelButton = null;
        [SkinControl((int)GUIControls.STATUSBUTTON)]
        protected GUIButtonControl statusButton = null;
        [SkinControl((int)GUIControls.SORTBUTTON)]
        protected GUISortButtonControl sortButton = null;
        [SkinControl((int)GUIControls.ABOUTBUTTON)]
        protected GUIButtonControl aboutButton = null;
        [SkinControl((int)GUIControls.SITESLIST)]
        protected GUIListControl siteList = null;
        
        [SkinControl((int)GUIControls.IMDBINFO)]
        protected GUITextScrollUpControl ImdbPlot = null;

        public int StatusID = 28111966;

        #endregion

        #region Dummy GUI Controls
        [SkinControl((int)GUIControls.DUMMYMAINVIEW)]
        protected GUILabelControl mainViewIndicator = null;
        [SkinControl((int)GUIControls.DUMMYSEARCHVIEW)]
        protected GUILabelControl searchViewIndicator = null;
        [SkinControl((int)GUIControls.DUMMYSTATUSVIEW)]
        protected GUILabelControl statusViewIndicator = null;
        #endregion

        #region Properties
        public ViewMode View {
            get {
                return _viewMode;
            }
            set {
                _viewMode = value;


                if (mainViewIndicator != null) mainViewIndicator.Visible = (_viewMode == ViewMode.MAIN);
                if (searchViewIndicator != null) searchViewIndicator.Visible = (_viewMode == ViewMode.SEARCH);
                if (statusViewIndicator != null) statusViewIndicator.Visible = (_viewMode == ViewMode.STATUS);

                if (_GUIInitialized)
                    GUIWindowManager.Process();

                switch (_viewMode) {
                    case ViewMode.NONE:
                        GUIUtils.SetProperty("#dlCentral.Header.Label", dlCentralUtils.PluginName());
                        GUIUtils.SetProperty("#dlCentral.Header.ShortLabel", string.Empty);
                        break;
                    case ViewMode.MAIN:
                        GUIUtils.SetProperty("#dlCentral.Header.Label", string.Format("{0} - {1}", dlCentralUtils.PluginName(), Localization.About));
                        GUIUtils.SetProperty("#dlCentral.Header.ShortLabel", Localization.About);
                        GUIControl.FocusControl(GetID, _defaultControlId);
                        break;
                    case ViewMode.SEARCH:
                        GUIUtils.SetProperty("#dlCentral.Header.Label", string.Format("{0} - {1}", dlCentralUtils.PluginName(), Localization.DownloadSearch));
                        GUIUtils.SetProperty("#dlCentral.Header.ShortLabel", Localization.DownloadSearch);
                        GUIControl.FocusControl(GetID, (int)GUIControls.SITESLIST);
                        break;
                    case ViewMode.STATUS:
                        GUIUtils.SetProperty("#dlCentral.Header.Label", string.Format("{0} - {1}", dlCentralUtils.PluginName(), Localization.DownloadStatus));
                        GUIUtils.SetProperty("#dlCentral.Header.ShortLabel", Localization.About);
                        GUIControl.FocusControl(GetID, _defaultControlId);
                        break;
                }
                UpdateButtonStates();
                PublishSearchProperties();
            }
        }
        private ViewMode _viewMode;

        public ListControlViewState ListControlViewState {
            get {
                return _listControlViewState;
            }
            set {
                _listControlViewState = value;
                UpdateSortButton();
            }
        }
        private ListControlViewState _listControlViewState;

        private PluginHandler CurrentHandler {
            get {
                return _currentHandler;
            }
            set {
                //if (_currentHandler == null)
                if (!_backupHandlerSet) {
                    _backupHandler = value;
                    _backupHandlerSet = true;
                }

                _currentHandler = value;

            }
        }
        private PluginHandler _currentHandler = null;
        private PluginHandler _backupHandler = null;

        public SiteSearchType ModifySearchSearchType {
            get {
                return _modifySearchSearchType;
            }
            set {
                if (value == SiteSearchType.IMDb) value = SiteSearchType.MOVIE;

                _modifySearchSearchType = value;

                GUIUtils.SetProperty("#dlCentral.ModifySearch.SearchType.Type", value.ToString());
            }
        }
        private SiteSearchType _modifySearchSearchType;
        #endregion

        #region GUIWindow Methods
        public override int GetID {
            get {
                return dlCentralGUIID;
            }
        }

        public override bool Init() {
            base.Init();
            core.Initialize();
            logger.Info("Initializing GUI");



            retriever.OnSiteSearchCompletedEvent += new Retriever.OnSiteSearchCompletedDelegate(retriever_OnSearchCompletedEvent);
            retriever.OnSiteSearchErrorEvent += new Retriever.OnSiteSearchErrorDelegate(retriever_OnSearchErrorEvent);
            retriever.OnDownloadEvent += new Retriever.OnDownloadDelegate(retriever_OnDownloadEvent);

            GUIUtils.SetProperty("#dlCentral.About", Localization.AboutText);

            // check if we can load the skin
            bool success = Load(GUIGraphicsContext.Skin + @"\dlCentral.xml");

            return success;
        }

        public override void DeInit() {
            base.DeInit();
            SettingsManager.Save();
        }

        protected override void OnPageLoad() {
            _GUIInitialized = false;
            _currentHandler = null;
            _backupHandler = null;
            _backupHandlerSet = false;
            _subtitleFilesForCurrentMedia.Clear();
            View = ViewMode.NONE;
            ModifySearchSearchType = SiteSearchType.NONE;
            ListControlViewState = ListControlViewState.SITES;

            _listSortMethod = Settings.SettingsManager.Properties.GUISettings.SortMethod;
            _listSortAsc = Settings.SettingsManager.Properties.GUISettings.SortAscending;

            GUIUtils.SetProperty("#currentmodule", dlCentralUtils.PluginName());

            //if (searchButton == null) {
            if (!CheckAndTranslateSkin()) {
                // if the component didn't load properly we probably have a bad skin file
                GUIUtils.ShowOKDialog(Localization.Error, Localization.CannotLoadSkin);
                GUIWindowManager.ShowPreviousWindow();
                logger.Error("Failed to load all components from skin file. Skin is outdated or invalid.");
                return;
            }

            base.OnPageLoad();
            _GUIInitialized = true;

            if (sortButton != null)
                sortButton.SortChanged += new SortEventHandler(OnSortChanged);

            // initialize properties
            InitSearchProperties();

            // initialize list control
            _lastSelectedSitesItemIndex = 0;
            _lastSelectedListItemIndex = 1;

            // get last active module  
            int lastActiveWindow = GUIWindowManager.GetPreviousActiveWindow();
            LoadFromPlugin(lastActiveWindow);
            logger.Debug("Entered plugin from {0} ({1})", CurrentHandler.PluginName, CurrentHandler.ID);
            View = ViewMode.SEARCH;
            FillSites();
            //Do some cleanup
            string CommPath = FileUtils.ensureBackSlash(Settings.SettingsManager.Properties.GeneralSettings.CommPath);
            FileUtils.CleanFolder(CommPath, "result*.*");
        }

        protected override void OnPageDestroy(int new_windowId) {
            base.OnPageDestroy(new_windowId);
            RetrieverAbort();


            Settings.SettingsManager.Properties.GUISettings.SortMethod = _listSortMethod;
            Settings.SettingsManager.Properties.GUISettings.SortAscending = _listSortAsc;

            if (sortButton != null)
                sortButton.SortChanged -= OnSortChanged;
            //if (CurrentHandler != null)
            //    CurrentHandler.Clear();
        }

        protected override void OnClicked(int controlId, GUIControl control, MediaPortal.GUI.Library.Action.ActionType actionType) {
            base.OnClicked(controlId, control, actionType);
            switch (controlId) {
                case (int)GUIControls.ABOUTBUTTON:
                    View = ViewMode.MAIN;
                    break;
                case (int)GUIControls.STATUSBUTTON:
                    if (retriever.IsStatusFileValidandPresent())
                        onShowDialogStatus();
                    else
                        GUIUtils.ShowNotifyDialog(Localization.Info, Localization.NoDownloadsActive, GUIUtils.dlCentralLogoThumbPath);
                    break;

                case (int)GUIControls.CANCELBUTTON:
                    if (View == ViewMode.MAIN)
                      View = ViewMode.SEARCH;
                    else
                      GUIWindowManager.ShowPreviousWindow();
                    break;

                case (int)GUIControls.SORTBUTTON:
                    OnShowDialogSortOptions();
                    break;

                case (int)GUIControls.SITESLIST:
                    // have to check action type for facade
                    if (actionType == MediaPortal.GUI.Library.Action.ActionType.ACTION_SELECT_ITEM) {
                        OnListSelection();
                    }
                    break;

            }
        }

        public override void OnAction(MediaPortal.GUI.Library.Action action) 
        {
            switch (action.wID) 
            {
                case    MediaPortal.GUI.Library.Action.ActionType.ACTION_PREVIOUS_MENU:
                    
                        if (GetFocusControlId() == (int)GUIControls.SITESLIST && RetrieverRunning())
                        {
                            RetrieverAbort();
                        }
                        else if (GetFocusControlId() == (int)GUIControls.SITESLIST && ListControlViewState != ListControlViewState.SITES)
                            OnListBack();
                            else if (View == ViewMode.MAIN) View = ViewMode.SEARCH;
                                else
                                    GUIWindowManager.ShowPreviousWindow();
                        break;
            
                case    MediaPortal.GUI.Library.Action.ActionType.ACTION_MOVE_DOWN:
                        base.OnAction(action);
                        if (GetFocusControlId() == (int)GUIControls.SITESLIST && ListControlViewState != ListControlViewState.SITES)
                            GetMovieInfo();
   
                        break;
 
                case MediaPortal.GUI.Library.Action.ActionType.ACTION_MOVE_UP:
                        base.OnAction(action);
                        if (GetFocusControlId() == (int)GUIControls.SITESLIST && ListControlViewState != ListControlViewState.SITES)
                        GetMovieInfo();
                        break;
                        
                    
                        default:
                            base.OnAction(action);
                            break;
            
            }
        }

        public override bool OnMessage(GUIMessage message) {
            return base.OnMessage(message);
        }
        #endregion

        #region Private Methods
        private bool LoadFromPlugin(int pluginID) {
            bool success = false;

            // try to grab our handler
            CurrentHandler = core.PluginHandlers[pluginID];
            if (CurrentHandler != null)
                success = CurrentHandler.Update();

            return success;
        }

        private void PerformSearch(object tag) {
            if (tag == null) return;

            if (CurrentHandler == null) return;

            if (RetrieverRunning()) {
                if (RetrieverCanceled())
                    RetrieverAbort();
                else
                    return;
            }
            _notificationDone = false;
//            retriever.OnProviderSearchErrorEvent -= retriever_OnProviderSearchErrorEvent;

            try {
                    if (tag is SettingsSite) {
             //       ShowWaitCursor();

                    SettingsSite settingsSite = tag as SettingsSite;

                    MediaDetail details = CurrentHandler.MediaDetail;
                    details.Site = tag as SettingsSite;
                    retriever.SearchForDownloads(details);
                }
            }
            catch (Exception e) {
                HideWaitCursor();
                logger.ErrorException("Error while retrieving downloads\n", e);
                GUIUtils.ShowNotifyDialog(Localization.Error, Localization.ErrorWhileRetrievingDownloads, GUIUtils.dlCentralLogoThumbPath);
            }
        }

        void retriever_OnSearchErrorEvent(Exception e)
        {
//            retriever.OnProviderSearchErrorEvent -= retriever_OnProviderSearchErrorEvent;
            HideWaitCursor();
            logger.ErrorException("Error while retrieving list\n", e);
            GUIUtils.ShowNotifyDialog(Localization.Error, string.Format(Localization.ErrorConnection, e.Message), GUIUtils.dlCentralLogoThumbPath);
            _notificationDone = false;
        }

        private bool RetrieverRunning() {
            if (retriever == null) return false;
            else return retriever.IsRunning();
        }

        private bool RetrieverCanceled() {
            if (retriever == null) return false;
            else return retriever.IsCanceled();
        }

        private void RetrieverAbort() {
            if (RetrieverRunning()) {
                retriever.Kill();
            }
            HideWaitCursor();
        }

        void retriever_OnSearchCompletedEvent(List<MediaDetail> downloadItems, bool isCanceled)
        {
 //           retriever.OnProviderSearchErrorEvent -= retriever_OnProviderSearchErrorEvent;
            HideWaitCursor();
            if (!isCanceled && !_notificationDone) {
                FillItemSearchResults(downloadItems);
            }
            _notificationDone = false;
        }

        private void PerformDownload(MediaDetail dlItem) {
            if (CurrentHandler == null) return;
            ShowWaitCursor();
            GUIWindowManager.Process();
            retriever.Download(dlItem);
        }

        private void retriever_OnDownloadEvent(MediaDetail mediaDetail, List<DownloadStatus> statusList)
        {
            HideWaitCursor();

            string heading = string.Empty;

            switch (mediaDetail.SearchType) {
                case SiteSearchType.TVSHOW:
                    heading = string.Format("{0}", mediaDetail.Title);
                    break;
                case SiteSearchType.MOVIE:
                    heading = "";
                    break;
                case SiteSearchType.IMDb:
                    heading = "";
                    break;
            }
            GUIUtils.ShowNotifyDialog(heading, Localization.DownloadQueued, GUIUtils.dlCentralLogoThumbPath);
        }

        private void countDownloads(List<DownloadStatus> statusList, out int succesful, out int canceled, out int errors)
        {
            succesful = 0;
            canceled = 0;
            errors = 0;

            if (statusList == null || statusList.Count == 0) return;

            foreach (DownloadStatus subtitleDownloadStatus in statusList)
            {
                if (subtitleDownloadStatus.Status == DownloadStatusStatus.Succesful)
                    succesful++;
                else if (subtitleDownloadStatus.Status == DownloadStatusStatus.Canceled || subtitleDownloadStatus.Status == DownloadStatusStatus.AlreadyExists)
                    canceled++;
                else
                    errors++;
            }
        }



        private void ShowWaitCursor() {
            waitCursor = new WaitCursor();
        }

        private void HideWaitCursor() {
            if (waitCursor != null) {
                waitCursor.Dispose();
                waitCursor = null;
            }
        }

        private void GetMovieInfo()
        {
            GUIListItem selectedItem = GUIControl.GetSelectedListItem(GetID, (int)GUIControls.SITESLIST);
            if (selectedItem != null)
            {
                if (selectedItem.MusicTag is MediaDetail)
                {
                    _lastSelectedListItemIndex = siteList.SelectedListItemIndex;
                    MediaDetail md = (MediaDetail)selectedItem.MusicTag;
                    if (md.MovieDBId == null && !md.IsInfoChecked) md.FillInfo();
                    if (md != null && md.SearchType == SiteSearchType.IMDb)
                    {
                       GUIUtils.SetProperty("#dlCentral.Search.Files.AllNames", md.Title);
                       GUIUtils.SetProperty("#dlCentral.Search.Media.Thumb", md.Thumb);
                       if (md.Plot != null)
                       {
                           ImdbPlot.Label = md.Plot;
                       }
                       else ImdbPlot.Label = "";
                    }
                }
            }
        }

        private void OnListSelection() {
            GUIListItem selectedItem = GUIControl.GetSelectedListItem(GetID, (int)GUIControls.SITESLIST);
            if (selectedItem != null) {
                if (selectedItem.MusicTag is SettingsSite) {
                    // search
                    _lastSelectedSitesItemIndex = siteList.SelectedListItemIndex;
                    PerformSearch(selectedItem.MusicTag);
                }
                else if (selectedItem.MusicTag is MediaDetail) {
                    _lastSelectedListItemIndex = siteList.SelectedListItemIndex;
                    PerformDownload((MediaDetail)selectedItem.MusicTag);
                    
                }
                else {
                    // back
                    OnListBack();
                }
            }
        }

        private void OnListBack() {
            FillSites();
        }

        private void InitSearchProperties() 
        {
           GUIUtils.SetProperty("#dlCentral.Search.Files.AllNames", string.Empty);
           GUIUtils.SetProperty("#dlCentral.Search.Media.TitleWithSE", string.Empty);
           GUIUtils.SetProperty("#dlCentral.Search.Media.Thumb", string.Empty);
           GUIUtils.SetProperty("#dlCentral.Search.Media.FanArt", string.Empty);
           GUIUtils.SetProperty("#dlCentral.Search.SearchType.Type", string.Empty);
        }


        private void PublishSearchProperties() {
           
             if (CurrentHandler == null) 
             {
                InitSearchProperties();
                return;
             }

            MediaDetail mediaDetail;
            mediaDetail = CurrentHandler.MediaDetail;

            string allFiles = string.Empty;
            for (int i = 1; i <= 10; i++) 
            {
                if (mediaDetail.Files != null && i <= mediaDetail.Files.Count) {
                    allFiles = allFiles + (string.IsNullOrEmpty(allFiles) ? mediaDetail.Files[i - 1].Name : "\n" + mediaDetail.Files[i - 1].Name);
                }
            }
            GUIUtils.SetProperty("#dlCentral.Search.Files.AllNames", allFiles);
            GUIUtils.SetProperty("#dlCentral.Search.Media.TitleWithSE", (!string.IsNullOrEmpty(mediaDetail.SeasonStr) && !string.IsNullOrEmpty(mediaDetail.EpisodeStr)) ? string.Format("{0} S{1:00}E{2:00}", mediaDetail.Title, mediaDetail.SeasonStr, mediaDetail.EpisodeStr) : mediaDetail.Title);
            GUIUtils.SetProperty("#dlCentral.Search.Media.Thumb", mediaDetail.Thumb);
            GUIUtils.SetProperty("#dlCentral.Search.Media.FanArt", mediaDetail.FanArt);
            GUIUtils.SetProperty("#dlCentral.Search.SearchType.Type", mediaDetail.SearchType.ToString());
            
        }


        private bool CheckAndTranslateSkin() {
            if (cancelButton != null )
            {
                cancelButton.Label = Localization.Back;
                statusButton.Label = Localization.Status;
                aboutButton.Label = Localization.About;
 
                return true;
            }
            else
                return false;
        }

        private void FillItemSearchResults(List<MediaDetail> MediaDetails)
        {

            if (MediaDetails != null && MediaDetails.Count > 0)
            {
                siteList.Clear();
                GUIListItem item = new GUIListItem();
                item.Label = "..";
                item.IsFolder = true;
                item.MusicTag = null;
                item.IconImage = "dlItemList.png";
                siteList.Add(item);

                foreach (MediaDetail mediaDetail in MediaDetails)
                {
                    SiteSortDetails searchDetails = new SiteSortDetails();
                    searchDetails.ListPosition = siteList.Count;
                    bool subtitleFileNameMatchesMedia = false;
                    searchDetails.Name = mediaDetail.Name;
                    searchDetails.Date = mediaDetail.Date;
                    GUIListItem siteListItem = new GUIListItem();
                    siteListItem.IsFolder = false;
                    siteListItem.Label = mediaDetail.Name;
                    siteListItem.Label2 = mediaDetail.Date.ToShortDateString();
                    siteListItem.Label3 = mediaDetail.TorrentInfo;
                    siteListItem.MusicTag = mediaDetail;
                    siteListItem.AlbumInfoTag = searchDetails;

                    siteListItem.IconImage = "dlItemList.png";

                    if (subtitleFileNameMatchesMedia)
                        siteListItem.IsPlayed = true;

                    siteList.Add(siteListItem);
                }

                ListControlViewState = ListControlViewState.SEARCHRESULTS;

                siteList.SelectedListItemIndex = _lastSelectedListItemIndex;

                GUIUtils.SetProperty("#itemcount", string.Concat((siteList.ListItems.Count - 1).ToString(), " ", Localization.DownloadS));

                OnSort();
                GetMovieInfo();
            }
            else {
                GUIUtils.ShowNotifyDialog(Localization.DownloadSearch, Localization.NoResultsFound, GUIUtils.dlCentralLogoThumbPath);
            }
        }

        private void FillSites() {

            siteList.Clear();
            int siteCounter = 0;
            foreach (SettingsSite settingsSite in Settings.SettingsManager.Properties.SiteSettings.Sites)
            {
                if (CurrentHandler.PluginName == "Moving Pictures" && settingsSite.MovieRemoteDirs.Count>0)
                { 
                GUIListItem siteListItem = new GUIListItem();
                siteListItem.IsFolder = false;
                siteListItem.Label = settingsSite.SiteName;
                if (settingsSite.SiteType == "Torrent") siteListItem.Label2 = Localization.TorrentSearch;
                siteListItem.MusicTag = settingsSite;
                siteListItem.IconImage = "dlItemList.png";

                siteList.Add(siteListItem);
                siteCounter++;
                }
                if (CurrentHandler.PluginName == "TVSeries" && settingsSite.TVRemoteDirs.Count > 0)
                {
                    GUIListItem siteListItem = new GUIListItem();
                    siteListItem.IsFolder = false;
                    siteListItem.Label = settingsSite.SiteName;
                    if (settingsSite.SiteType == "Torrent") siteListItem.Label2 = Localization.TorrentSearch; 
                    siteListItem.MusicTag = settingsSite;
                    siteListItem.IconImage = "dlItemList.png";
                    siteList.Add(siteListItem);
                    siteCounter++;
                }
                if (CurrentHandler.PluginName == "Movies" && settingsSite.MovieRemoteDirs.Count > 0)
                {
                    GUIListItem siteListItem = new GUIListItem();
                    siteListItem.IsFolder = false;
                    siteListItem.Label = settingsSite.SiteName;
                    if (settingsSite.SiteType == "Torrent") siteListItem.Label2 = Localization.TorrentSearch;
                    siteListItem.MusicTag = settingsSite;
                    siteListItem.IconImage = "dlItemList.png";

                    siteList.Add(siteListItem);
                    siteCounter++;
                }
            }
            ListControlViewState = ListControlViewState.SITES;

            siteList.SelectedListItemIndex = _lastSelectedSitesItemIndex;
            _lastSelectedSitesItemIndex = 0;
            _lastSelectedListItemIndex = 1;
            if (siteCounter > 0) {
                GUIUtils.SetProperty("#itemcount", string.Concat(siteCounter.ToString(), " ", Localization.Sites));
            }
        }


        private void onShowDialogStatus()
        {
            GUIDialogStatus dlg = (GUIDialogStatus)GUIWindowManager.GetWindow(StatusID);
      //      statusDialog.Height = 400 + (itemCounter*60);
      //      statusDialog.KeepAspectRatio = true;
            ViewMode oldView = _viewMode; 
            View = ViewMode.STATUS;
            dlg.Reset();
            
            dlg.DoModal(GUIWindowManager.ActiveWindow);
            View = oldView;

        }
            

        

        private void OnShowDialogSortOptions() {
            List<GUIListItem> items = new List<GUIListItem>();
            items.Add(new GUIListItem(Localization.SortByName));
            items.Add(new GUIListItem(Localization.SortByDate));

            int dlgResult = GUIUtils.ShowMenuDialog(Localization.Sorting, items, (int)_listSortMethod);

            if (dlgResult < 0) return;

            switch (dlgResult) {
                case 0:
                    _listSortMethod = ItemSortMethod.ItemName;
                    break;
                case 1:
                    _listSortMethod = ItemSortMethod.ItemDate;
                    break;
            }

            OnSort();
            GUIControl.FocusControl(GetID, (int)GUIControls.SORTBUTTON);
        }

        private void OnSort() {
            siteList.Sort(new GUIListItemComparer(_listSortMethod, _listSortAsc));
            UpdateSortButton();
        }

        private void UpdateSortButton() {
            string labelSort = Localization.Sort;

            if (View == ViewMode.SEARCH && ListControlViewState == ListControlViewState.SEARCHRESULTS) {
                switch (_listSortMethod) {
                    case ItemSortMethod.ItemName:
                        labelSort = string.Format(Localization.SortBy, Localization.Name);
                        break;
                    case ItemSortMethod.ItemDate:
                        labelSort = string.Format(Localization.SortBy, Localization.Date);
                        break;
                }
                if (sortButton != null)
                    sortButton.Disabled = false;
            }
            else {
                if (sortButton != null)
                    sortButton.Disabled = true;
            }
            if (sortButton != null) {
                sortButton.Label = labelSort;
                sortButton.IsAscending = _listSortAsc;
            }
        }

        private void OnSortChanged(object sender, SortEventArgs e) {
            _listSortAsc = e.Order != SortOrder.Descending;
            OnSort();
            GUIControl.FocusControl(GetID, (int)GUIControls.SORTBUTTON);
        }

        private void UpdateButtonStates() {
            UpdateSortButton();
        }



        #endregion
    }

    public enum ViewMode {
        NONE,
        MAIN,
        SEARCH,
        STATUS
    }

    public enum ListControlViewState {
        SITES,
        SEARCHRESULTS
    }
}
